package com.zheng.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zheng.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author lenovo
 */
@RestController
public class DeptController {
    private final String REST_URL_PREFIX = "http://provider-dept";

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/dept/list")
    @HystrixCommand(fallbackMethod = "hystrixSelect")
    public ArrayList<Dept> select(){
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list",ArrayList.class);
    }
    @RequestMapping("/dept/add")
    public boolean addDept(Dept dept){
        HashMap<String, Object> map = new HashMap<>();
        System.out.println(dept);
//        在这里我不能直接传递Dept这个对象！
        map.put("deptName",dept.getDeptName());
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/add?deptName={deptName}",Boolean.class,map);
    }
    @RequestMapping("/dept/get/{id}")
    @HystrixCommand(fallbackMethod = "hystrixGet")
    public Dept get(@PathVariable("id")int id){
        Dept dept = restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class);
        if(dept==null){
            throw new RuntimeException("数据库不存在该数据！");
        }
        return dept;
    }

    public Dept hystrixGet(@PathVariable("id")int id){
        return new Dept().setDeptId(id).setDeptName("ID"+id+"未找到,该服务已由Hystrix熔断！").setDeptDatabase("未找到该数据库！");
    }
    public ArrayList<Dept> hystrixSelect() {
        ArrayList<Dept> list = new ArrayList<>();
        list.add(new Dept().setDeptId(-1).setDeptName("服务器繁忙，请稍候重试！").setDeptDatabase("数据库繁忙！"));
        return list;
    }
}
